import React, {Component} from 'react';
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheImage from '@/components/TheImage'
import {Modal, Form, Input, Pagination, Alert, Button, Space, message, Switch, InputNumber, Checkbox, Table} from 'antd'
import {apiGoodsStockInfo} from '@/request/marketingTool'
import {exportSheetTable, exportTable} from '@/utils/exportTable'
// import '@/views/marketingTool/kill/style.less'
import dayjs from 'dayjs'
import moment from "moment";

const {Column, ColumnGroup} = Table;

class Goods extends Component {
    constructor(props) {
        super(props)
        this.formRef = React.createRef()
        this.state = {
            goodsColumns: [
                {
                    title: "商品ID",
                    key: "goodsId",
                    width: 100,
                    dataIndex: "goodsId",
                },
                {
                    title: "商品名称",
                    key: "goodsName",
                    dataIndex: "goodsName",
                    onCell: () => {
                        return {
                            style: {
                                maxWidth: 160,
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                cursor: 'pointer'
                            }
                        }
                    }
                },
                {
                    title: "商品图片",
                    key: "goodsShowImages",
                    dataIndex: "goodsShowImages",
                    render: (text) => {
                        if (text) {
                            let str = text.split(',')[0]
                            return <div>
                                {
                                    text.split(',').map(item => <span style={{marginRight: 10}}><TheImage src={item}
                                                                                                          width={80}
                                                                                                          height={80}/></span>)
                                }
                            </div>
                        }
                    }
                },
                {
                    title: "所属类目",
                    key: "goodsClassifyName",
                    dataIndex: "goodsClassifyName",
                },
                {
                    title: "商品原价",
                    key: "originalPrice",
                    dataIndex: "originalPrice",
                    render: (text, render) => {
                        return <React.$Price price={render.originalPrice || 0
                        }/>
                    },
                },
                {
                    title: "商品现价",
                    key: "currentPrice",
                    dataIndex: "currentPrice",
                    render: (text, render) => {
                        return <React.$Price price={render.currentPrice || 0
                        }/>
                    },
                },
                {
                    title: "商品状态",
                    key: "goodsStatus",
                    dataIndex: "goodsStatus",
                    render: (text, render) => {
                        return text === 'Y' ? '上架' : '下架'
                    },
                },
                {
                    title: "上次操作时间",
                    key: "updateTime",
                    dataIndex: "updateTime",
                }
            ],

            dataSource: [],
            isModalShow: false,
            pageData: {
                pageNo: 1,
                pageSize: 10,
                totalCount: 0,
            },
            searchForm: {
                goodsName: '',
                goodsId: ''
            },
            alertType: '',
            importInfo: {},
            goodsList: [],
            goodsPage: {
                pageNo: 1,
                pageSize: 10,
                totalCount: 0,
            },
            dataSourceCopy: [],
            canImport: false,
            disabledKeys: []
        }
    }

    componentDidMount() {
        this.getData()
        this.setState({
            dataSource: this.props.initData
        })
    }

    resetData() {
        this.setState({
            dataSource: []
        })
    }

    componentDidUpdate(nextProps) {
    }

    isLimit(e, key, index, skuIndex) {
        const dataSource = [...this.state.dataSource]
        const {pageNo, pageSize} = this.state.pageData
        const currentIndex = (pageNo - 1) * pageSize + index
        dataSource[currentIndex].skuInfoVos[skuIndex].isLimit = dataSource[currentIndex].skuInfoVos[skuIndex].isLimit ? 0 : 1
        this.setState({
            dataSource
        })
    }

    aInputChange(e, key, index, skuIndex) {
        const dataSource = [...this.state.dataSource]
        const {pageNo, pageSize} = this.state.pageData
        const currentIndex = (pageNo - 1) * pageSize + index
        if (key == 'killSort') {
            dataSource[currentIndex][key] = e
            dataSource[currentIndex][key + '_tip'] = null
        } else {
            dataSource[currentIndex].skuInfoVos[skuIndex][key] = e
            dataSource[currentIndex].skuInfoVos[skuIndex][key + '_tip'] = null

        }
        this.setState({
            dataSource
        }, () => {
            console.log(this.state.dataSource, 'dataSource')
        })
    }

    isJoinChange(index, skuIndex) {
        const dataSource = [...this.state.dataSource]
        const {pageNo, pageSize} = this.state.pageData
        const currentIndex = (pageNo - 1) * pageSize + index
        dataSource[currentIndex].skuInfoVos[skuIndex].isJoin = dataSource[currentIndex].skuInfoVos[skuIndex].isJoin ? 0 : 1
        dataSource[currentIndex].skuInfoVos[skuIndex] = {
            ...dataSource[currentIndex].skuInfoVos[skuIndex],
            a_stock: null,
            a_price: null,
            quota_count: null,
            isLimit: false,
            virtualCount: null
        }
        this.setState({
            dataSource
        }, () => {
            console.log(this.state.dataSource, 'dataSource')
        })
    }

    // 获取商品列表
    async getData() {
        const {goodsName, goodsId} = this.state.searchForm
        const {pageNo, pageSize} = this.state.goodsPage
        let res = await apiGoodsStockInfo({
            pageNo, pageSize, goodsName: goodsName ? goodsName : '',
            goodsId: goodsId ? goodsId : '', storeStatus: 'Y', goodsStatus: 'Y', reviewStatus: 'T'
        })
        if (res.code === 0) {
            this.state.goodsPage.totalCount = res.totalCount
            this.setState({
                goodsList: [],
                goodsPage: this.state.goodsPage
            }, () => this.setState({
                goodsList: res.data,
            }))
        } else {
            React.$message({
                type: 'error',
                content: res.codeMessage
            })
        }
    }

    delGoods(record, index) {
        // React.$confirm({
        //     title: "提示",
        //     type: 'warning',
        //     content: "删除商品可能导致正在购买的消费者无法正常下单，是否继续删除？",
        //     onOk: async () => {
        //         const dataSource = [...this.state.dataSource]
        //         dataSource.splice(index, 1)
        //         this.setState({
        //             dataSource: dataSource
        //         })
        //     }
        // });
        const dataSource = [...this.state.dataSource]
        // dataSource.splice(index, 1)
        const {pageNo, pageSize} = this.state.pageData
        dataSource.splice((pageNo - 1) * pageSize + index, 1)
        this.setState({
            dataSource: dataSource
        }, () => {
            this.props.setData(this.state.dataSource)
        })
    }

    // 选择商品弹框
    goChoose() {
        this.setState({
            isModalShow: true,
            dataSourceCopy: [...this.state.dataSource]
        }, () => {
            this.getSelectKeys()
            this.resetForm()
        })
    }

    //商品批量导入
    async importGoods(e) {
        const {mode, activityId} = this.props
        const activityTime = this.props.getFieldsValue('activityTime')
        let formData = new FormData()
        formData.append('file', e.target.files[0])
        formData.append('startTime', activityTime ? dayjs(activityTime[0]).format('YYYY-MM-DD HH:mm:ss') : '')
        formData.append('endTime', activityTime ? dayjs(activityTime[1]).format('YYYY-MM-DD HH:mm:ss') : '')
        e.target.value = ""
        if (mode === 'edit') {
            formData.append('activityId', activityId)
            fetch(React.$BaseUrl + '/market/api/seckillActivity/updateGoods',
                {
                    method: "post",
                    headers: {
                        RSnetToken: sessionStorage.getItem('RSnetToken')
                    },
                    body: formData,
                })
                .then((res) => {
                    res.json().then(result => {
                        if (result.code === 0) {
                            console.log(result, 'ress');
                            const {
                                code, data, codeMessage
                            } = result
                            if (code === 0) {
                                const {goodList, status} = data
                                if (status === 'N') {
                                    this.setState({
                                        alertType: 'error',
                                        importInfo: {
                                            title: '导入失败！',
                                            data: data,
                                            message: codeMessage,
                                            failFile: data.failFile
                                        }
                                    })
                                    return
                                }
                                const dataSource = []
                                goodList.forEach(item => {
                                    const good = {
                                        killSort: item.sort,
                                        goodsId: item.goodsId,
                                        goodsName: item.goodsName,
                                    }
                                    let curLowPrice = item.skuList[0].skuCurrentPrice, curLowIndex = 0
                                    good.skuInfoVos = item.skuList.map((sku, index) => {
                                        if (sku.skuCurrentPrice <= curLowPrice) {
                                            curLowIndex = index
                                            curLowPrice = sku.skuCurrentPrice
                                        }
                                        return {
                                            "materialId": sku.materialId,//物料编码
                                            "goodsSkuId": sku.goodsSkuId,//skuId
                                            "isJoin": sku.skuEnabled ? 0 : 1,
                                            skuAttributes: sku.skuAttributes || [],
                                            skuStock: sku.skuStock,
                                            "a_stock": sku.activityStock,//活动库存
                                            skuCurrentPrice: sku.skuCurrentPrice ? (sku.skuCurrentPrice / 100).toFixed(2) : 0,
                                            "a_price": sku.activityGoodsSkuPrice ? (sku.activityGoodsSkuPrice / 100).toFixed(2) : 0,//活动价格
                                            'isLimit': sku.quota === -1 ? 0 : 1,
                                            "quota_count": sku.quota === -1 ? null : sku.quota,
                                            "virtualCount": sku.virtualNum//虚拟抢购件数
                                        }
                                    })
                                    good.skuInfoVos[curLowIndex].isJoin = 0
                                    good.skuInfoVos[curLowIndex].isLow = true
                                    dataSource.push(good)
                                })
                                this.setState({
                                    dataSource
                                })

                            } else {
                                message.error(codeMessage)
                            }
                        } else {
                            message.error(result.codeMessage)
                        }
                    })
                })
                .catch((res) => {
                    React.$message({
                        type: 'error',
                        content: '导入失败'
                    })
                })
                .finally(() => {
                });
        } else {
            fetch(React.$BaseUrl + '/seckillActivity/importGood',
                {
                    method: "post",
                    headers: {
                        RSnetToken: sessionStorage.getItem('RSnetToken')
                    },
                    body: formData,
                })
                .then((res) => {
                    res.json().then(result => {
                        if (result.code === 0) {
                            const {
                                code, data, codeMessage
                            } = result
                            if (code === 0) {
                                const {goodList, status} = data
                                if (status === 'N') {
                                    this.setState({
                                        alertType: 'error',
                                        importInfo: {
                                            title: '导入失败！',
                                            data: data,
                                            message: codeMessage,
                                            failFile: data.failFile
                                        }
                                    })
                                    return
                                }
                                const dataSource = []
                                goodList.forEach(item => {
                                    const good = {
                                        killSort: item.sort,
                                        goodsId: item.goodsId,
                                        goodsName: item.goodsName,
                                    }
                                    let curLowPrice = item.skuList[0].skuCurrentPrice, curLowIndex = 0
                                    good.skuInfoVos = item.skuList.map((sku, index) => {
                                        if (sku.skuCurrentPrice <= curLowPrice) {
                                            curLowIndex = index
                                            curLowPrice = sku.skuCurrentPrice
                                        }
                                        return {
                                            "materialId": sku.materialId,//物料编码
                                            "goodsSkuId": sku.goodsSkuId,//skuId
                                            "isJoin": sku.skuEnabled ? 0 : 1,
                                            skuAttributes: sku.skuAttributes || [],
                                            skuStock: sku.skuStock,
                                            "a_stock": sku.activityStock,//活动库存
                                            skuCurrentPrice: sku.skuCurrentPrice ? (sku.skuCurrentPrice / 100).toFixed(2) : 0,
                                            "a_price": sku.activityGoodsSkuPrice ? (sku.activityGoodsSkuPrice / 100).toFixed(2) : 0,//活动价格
                                            'isLimit': sku.quota === -1 ? 0 : 1,
                                            "quota_count": sku.quota === -1 ? null : sku.quota,
                                            "virtualCount": sku.virtualNum//虚拟抢购件数
                                        }
                                    })
                                    good.skuInfoVos[curLowIndex].isJoin = 0
                                    good.skuInfoVos[curLowIndex].isLow = true
                                    dataSource.push(good)
                                })
                                this.setState({
                                    dataSource
                                })

                            } else {
                                message.error(codeMessage)
                            }
                        } else {
                            message.error(result.codeMessage)
                        }
                    })
                })
                .catch((res) => {
                    React.$message({
                        type: 'error',
                        content: '导入失败'
                    })
                })
                .finally(() => {
                });
        }

    }

    // 选择商品保存
    handleOk = () => {
        this.setState({
            isModalShow: false,
            dataSource: this.state.dataSourceCopy
        }, () => {
            this.props.setData(this.state.dataSource)
        })
    }
    // 选择商品取消
    handleCancel = () => {
        this.setState({
            isModalShow: false
        })
    }

    // 获取当前勾选得key
    getSelectKeys() {
        const selectedRowKeys = this.state.dataSourceCopy.map(item => item.goodsId)
        this.setState({
            selectedRowKeys
        })
    }

    //批量勾选
    onSelect = (record, selected, selectedRows) => {
        let dataSourceCopy = [...this.state.dataSourceCopy]
        if (this.props.type === 'radio') {
            dataSourceCopy = []
        }
        if (selected) {
            let curLowPrice = record.skuInfoVos[0].skuCurrentPrice, curLowIndex = 0
            record.skuInfoVos.forEach((sku, index) => {
                sku.isJoin = 0
                if (sku.skuCurrentPrice <= curLowPrice) {
                    curLowIndex = index
                    curLowPrice = sku.skuCurrentPrice
                }
            })
            record.skuInfoVos[curLowIndex].isJoin = 0
            record.skuInfoVos[curLowIndex].isLow = true

            dataSourceCopy.push({...record})
        } else {
            const delIndex = dataSourceCopy.findIndex(item => item.goodsId === record.goodsId)
            dataSourceCopy.splice(delIndex, 1)
        }
        // console.log(dataSourceCopy)
        this.setState({
            dataSourceCopy
        }, () => this.getSelectKeys())
    }
    onSelectAll = (selected, rows, newRow) => {
        let dataSourceCopy = [...this.state.dataSourceCopy]
        if (selected) {
            newRow.forEach((item, index) => {
                let curLowPrice = item.skuInfoVos[0].skuCurrentPrice, curLowIndex = 0
                item.skuInfoVos.forEach((sku, index) => {
                    sku.isJoin = 0
                    if (sku.skuCurrentPrice <= curLowPrice) {
                        curLowIndex = index
                        curLowPrice = sku.skuCurrentPrice
                    }
                })
                item.skuInfoVos[curLowIndex].isJoin = 0
                item.skuInfoVos[curLowIndex].isLow = true

            })
            dataSourceCopy = dataSourceCopy.concat(...newRow)
        } else {
            const newKeys = newRow.map(item => item.goodsId)
            dataSourceCopy = dataSourceCopy.filter(item => !newKeys.includes(item.goodsId))
        }
        this.setState({
            dataSourceCopy
        }, () => this.getSelectKeys())
    }

    pageChange(e) {
        this.state.pageData.pageNo = e
        this.setState({
            pageData: this.state.pageData
        })
    }

    // 弹框分页
    goodsPageChange(e) {
        this.state.goodsPage.pageNo = e
        this.setState({
            goodsPage: this.state.goodsPage
        }, () => {
            this.getData()
        })
    }

    // 弹框搜索
    searchGoods() {
        const values = this.formRef.current.getFieldsValue()
        this.setState({
            searchForm: {
                goodsId: values.goodsId,
                goodsName: values.goodsName
            },
            goodsPage: {
                pageNo: 1,
                pageSize: this.state.goodsPage.pageSize,
                total: 0
            }
        }, () => this.getData())
    }

    // 弹框重置
    resetForm() {
        this.formRef.current.resetFields()
        this.setState({
            searchForm: {
                goodsId: '',
                goodsName: ''
            }
        }, () => this.getData())
    }

    downloadExcel = () => {
        const a = document.createElement('a')
        a.href = this.state.importInfo.failFile
        document.body.append(a)
        a.click()
        a.remove()
    }
    onMouseEnter = () => {
        const activityTime = this.props.getFieldsValue('activityTime', false)
        this.setState({
            canImport: activityTime
        })
    }

    uploadBefore() {
        this.props.getFieldsValue('activityTime', true)
    }

    downloadDemo() {
        const {dataSource} = this.state
        const {mode} = this.props

        if (mode === 'add') {
            const a = document.createElement('a')
            a.href = 'https://hqmimage.oss-cn-beijing.aliyuncs.com/%E6%96%B0%E5%A2%9E%E7%A7%92%E6%9D%80%E5%95%86%E5%93%81%E6%A8%A1%E6%9D%BF.xlsx'
            document.body.append(a)
            a.click()
            a.remove()
        } else {
            let tH_data = [
                {prop: 'index', title: '序号'},
                {prop: 'goodsId', title: '商品id'},
                {prop: 'skuId', title: 'skuId'},
                {prop: 'skuEnabled', title: '是否参加活动（0/不参加，1/参加）'},
                {prop: 'activityStock', title: '活动库存'},
                {prop: 'activityGoodsSkuPrice', title: '活动价'},
                {prop: 'quota', title: '限购（-1为不限购）'},
                {prop: 'sort', title: '排序（同一个spu保持一致）'},
                {prop: 'virtualNum', title: '虚拟抢购件数'}
            ]
            let tB_data = []
            this.state.dataSource.forEach((item) => {
                item.skuInfoVos.forEach((sku, index) => {
                    tB_data.push({
                        index: tB_data.length + 1,
                        goodsId: item.goodsId,
                        skuId: sku.goodsSkuId,
                        skuEnabled: sku.isJoin ? 0 : 1,
                        activityStock: sku.a_stock,
                        activityGoodsSkuPrice: sku.a_price ? sku.a_price * 100 : 0,
                        quota: sku.hasOwnProperty('isLimit') && sku.isLimit && sku.isJoin === 0 ? sku.quota_count : -1,
                        sort: item.killSort,
                        virtualNum: sku.virtualCount,
                    })
                })
            })
            exportTable(tH_data, tB_data)
            return
            exportSheetTable({
                fileName: '秒杀数据模板', tH_data: tH_data, tB_data: tB_data, isSheet: true
            })
        }
    }

    render() {
        const {
            columns,
            dataSource,
            isModalShow,
            canImport,
            pageData,
            alertType,
            importInfo,
            selectedRowKeys,
            goodsColumns,
            goodsList,
            goodsPage
        } = this.state
        const {disabledKeys, mode, type} = this.props
        // console.log(disabledKeys)
        const rowSelection = {
            selectedRowKeys,
            onSelect: this.onSelect,
            onSelectAll: this.onSelectAll,
            getCheckboxProps: (record) => {
                return {
                    disabled: disabledKeys.includes(record.goodsId),
                }
            },
        };
        if (type === 'radio') {
            rowSelection.type = 'radio'
        }
        // console.log(disabledKeys, 'disabledKeys');
        return (
            <div className='noCanJoinGood'>
                {
                    mode !== 'view' ? <div className='btnList'>
                        {/*<TheButton type="default" size="middle" className="goodsImport" onClick={() => this.goChoose()} style={{marginBottom:"15px"}}>选择商品</TheButton>*/}
                        {/*<TheButton type="default" size="middle" className="goodsImport" onClick={() => { this.uploadBefore() }} onMouseEnter={this.onMouseEnter} >*/}
                        {/*    <input type="file" className="importBtn" onChange={(e) => this.importGoods(e)} style={{ display: canImport ? 'block' : 'none' }} /> {mode === 'edit' ? '批量修改' : '批量导入'}*/}
                        {/*</TheButton>*/}
                        {/*<TheButton type="link" size="middle" className="downloadDemo" onClick={() => this.downloadDemo()}>*/}
                        {/*    下载导入文件模板*/}
                        {/*</TheButton>*/}
                    </div> : null
                }

                <Table dataSource={dataSource} bordered size="middle"
                       pagination={{
                           showTotal: () => `共${dataSource.length}条`,
                           pageSize: pageData.pageSize,
                           onChange: (e) => this.pageChange(e)
                       }}
                       rowKey={(record) => record.goodsId}
                       scroll={{x: "max-content", y: '57vh'}}
                >
                    <Column title="商品ID" dataIndex="goodsId" key="goodsId" align={"center"} width={200}/>
                    <Column title="商品名称" dataIndex="goodsName" key="goodsName" align={"center"} width={250} ellipsis={true}/>
                    <Column title="商品图片" dataIndex="goodsShowImages" key="goodsShowImages"
                            style={{padding: 0}} align={"center"}
                            render={(text, record, index) => {
                                if (text) {
                                    let str = text.split(',')[0]
                                    return <div>
                                        {
                                            text.split(',').map(item => <span style={{marginRight: 10}}><TheImage
                                                src={item} width={80} height={80}/></span>)
                                        }
                                    </div>
                                }
                            }}
                    />
                    <Column title="所属类目" align={"center"} dataIndex="goodsClassifyName" key="goodsClassifyName"/>
                    <Column title="商品原价" align={"center"} dataIndex="originalPrice" key="originalPrice"
                            render={(text, record, index) => {
                                return <React.$Price price={record.originalPrice || 0
                                }/>
                            }}
                    />
                    <Column title="商品现价" align={"center"} dataIndex="currentPrice" key="currentPrice"
                            render={(text, record, index) => {
                                return <React.$Price price={record.currentPrice || 0
                                }/>
                            }}
                    />
                    <Column title="商品状态" align={"center"} dataIndex="goodsStatus" key="goodsStatus" width={100}
                            render={(text, record, index) => {
                                return text === 'Y' ? '上架' : '下架'
                            }}
                    />
                    <Column title="操作时间" align={"center"} dataIndex="updateTime" key="updateTime" width={100}
                            render={(text, record, index) => {
                                return record.updateTime ? text : (record.lastUpdateTime === null ? '/' : moment(record.lastUpdateTime).format('YYYY-MM-DD HH:mm:ss'))
                            }}
                    />
                    {
                        mode !== 'view' ? <Column
                            title="操作"
                            key="action"
                            fixed="right"
                            align={"center"}
                            render={(text, record, index) => {
                                const {disabledKeys} = this.props
                                return disabledKeys.includes(record.goodsId) ? "无法删除" :
                                    <TheButton onClick={() => this.delGoods(record, index)}>删除</TheButton>
                            }}
                        /> : null
                    }
                </Table>
                <Modal
                    width={'80%'} title={'选择商品'} visible={isModalShow} onOk={this.handleOk}
                    onCancel={this.handleCancel}>
                    <Form layout={'inline'} ref={this.formRef}>
                        <Form.Item name="goodsName">
                            <Input placeholder="商品名称" style={{width: 300}}/>
                        </Form.Item>
                        <Form.Item name="goodsId"
                                   rules={[{
                                       pattern: new RegExp(/^[1-9]\d*$/, "g"),
                                       message: `请输入正确的数字ID`
                                   }]}>
                            <Input placeholder="商品ID" style={{width: 300}}/>
                        </Form.Item>
                        <Form.Item>
                            <TheButton size="middle" className="goodsImport" type="primary"
                                       onClick={() => this.searchGoods()}>查询</TheButton>
                            <TheButton size="middle" type="default" onClick={() => this.resetForm()}>重置</TheButton>
                        </Form.Item>
                    </Form>
                    <TheTable
                        style={{margin: '10px 0'}}
                        scroll={{x: "max-content", y: '57vh'}}
                        columns={goodsColumns}
                        dataSource={goodsList}
                        rowSelection={rowSelection}
                        rowKey={(record) => record.goodsId}
                    />
                    <Pagination style={{textAlign: 'right'}} size="small" current={goodsPage.pageNo}
                                total={goodsPage.totalCount} showSizeChanger={false}
                                onChange={this.goodsPageChange.bind(this)}/>

                </Modal>
                {
                    alertType &&
                    <div style={{width: '100vw', height: '100vh', position: 'fixed', left: 0, top: 0, zIndex: 9999}}>
                        <Alert
                            style={{margin: '100px auto', width: 500}}
                            message={importInfo.title}
                            showIcon
                            description={importInfo.message}
                            type={alertType}
                            closable
                            onClose={() => this.onAlertClose()}
                            action={
                                alertType === 'error' && <Space direction="vertical">
                                    <Button size="small" type="primary" onClick={this.downloadExcel}>
                                        下载文件
                                    </Button>
                                </Space>
                            }
                        />
                    </div>
                }
            </div>
        );
    }
}

Goods.propTypes = {}
Goods.defaultProps = {}
export default Goods
